<?php

namespace App\Containers\AppSection\Questionnaire\UI\API\Requests;

use App\Containers\AppSection\Ban\Traits\ProfilesBan;
use App\Containers\AppSection\Ban\Traits\UsersBan;
use App\Containers\AppSection\Questionnaire\Tasks\FindFieldByIdTask;
use App\Containers\AppSection\Questionnaire\Tasks\FindResponseByIdTask;
use App\Containers\AppSection\Questionnaire\Traits\IsOwnerProfileTrait;
use App\Containers\AppSection\Questionnaire\Traits\UpdateQuestionnaireRequestTrait;
use App\Ship\Parents\Requests\Request;
use Illuminate\Validation\Rule;

class UpdateResponseRequest extends Request
{
    use IsOwnerProfileTrait;
    use UpdateQuestionnaireRequestTrait;
    use ProfilesBan;
    use UsersBan;

    /**
     * Define which Roles and/or Permissions has access to this request.
     */
    protected array $access = [
        'permissions' => '',
        'roles' => 'borrower|investor',
    ];

    /**
     * Id's that needs decoding before applying the validation rules.
     */
    protected array $decode = [
        // 'id',
    ];

    /**
     * Defining the URL parameters (e.g, `/user/{id}`) allows applying
     * validation rules on them and allows accessing them like request data.
     */
    protected array $urlParameters = [
        // 'id',
    ];

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $response = app(FindResponseByIdTask::class)->run($this->id);
        $valuesRules = [
            'values' => ['bail', 'required', 'array', $this->valuesRule($response->form->fields)],
            'values.*.field_id' => ['bail', 'required', Rule::exists('questionnaire_fields', 'id')],
            'values.*.person' => ['bail', 'required', 'numeric'],
        ];
        $values = $this->getInputByKey('values');
        foreach ($values as &$v) {
            $v['field'] = app(FindFieldByIdTask::class)->run($v['field_id']);
        }

        foreach ($values as $key => $value) {
            $valuesRules = array_merge($valuesRules, [
                "values.$key" => ['bail', 'required', $this->valueRule($values, $value['field'], false)]
            ]);
        }
        return $valuesRules;
    }

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->check([
            'hasAccess',
            'isOwnerProfile',
            'profileIsNotBanned',
            'userIsNotBanned'
        ]);
    }
}
